<template>
  <div class="leave-application-container">
    <h2 class="page-title">请假申请</h2>

    <el-form
        :model="leaveForm"
        :rules="rules"
        ref="leaveFormRef"
        class="leave-form"
    >
      <el-form-item label="员工姓名" prop="employeeName">
        <el-input v-model="leaveForm.employeeName" disabled />
      </el-form-item>

      <el-form-item label="员工电话" prop="phone">
        <el-input v-model="leaveForm.phone" disabled />
      </el-form-item>

      <!-- 开始日期 -->
      <el-form-item label="请假开始日期" prop="startDate">
        <el-date-picker
            v-model="leaveForm.startDate"
            type="date"
            placeholder="选择请假开始日期"
            :disabled-date="disabledStart"
            style="width: 100%;"
            @change="handleStartChange"
        />
      </el-form-item>

      <!-- 结束日期 -->
      <el-form-item label="请假结束日期" prop="endDate">
        <el-date-picker
            v-model="leaveForm.endDate"
            type="date"
            placeholder="选择请假结束日期"
            :disabled-date="disabledEnd"
            style="width: 100%;"
        />
      </el-form-item>

      <el-form-item label="请假原因" prop="reason">
        <el-input
            type="textarea"
            v-model="leaveForm.reason"
            :rows="4"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitLeaveApplication" >
          提交申请
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import http from '@/axios/http'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/userStore'

/* ---------- 数据 ---------- */
const userStore = useUserStore()
const leaveFormRef = ref(null)

const leaveForm = reactive({
  employeeName: '',
  phone: '',
  startDate: null,
  endDate: null,
  reason: ''
})

/* ---------- 校验规则 ---------- */
const rules = reactive({
  startDate: [
    { required: true, message: '请选择请假开始日期', trigger: 'blur' }
  ],
  endDate: [
    { required: true, message: '请选择请假结束日期', trigger: 'blur' }
  ],
  reason: [
    { required: true, message: '请填写请假原因', trigger: 'blur' }
  ]
})

/* ---------- 日期禁用 & 联动 ---------- */
// 【新增】禁止选择今天之前
function disabledStart(time) {
  return time.getTime() < Date.now() - 8.64e7
}
// 【新增】结束日期必须 ≥ 开始日期
function disabledEnd(time) {
  if (!leaveForm.startDate) return false
  const start = new Date(leaveForm.startDate)
  return time.getTime() < start.getTime()
}
// 【新增】当重新选择开始日期后，若结束日期早于开始，则自动清空结束日期
function handleStartChange() {
  if (
      leaveForm.endDate &&
      new Date(leaveForm.endDate) < new Date(leaveForm.startDate)
  ) {
    leaveForm.endDate = null
  }
}

/* ---------- 获取员工信息 ---------- */
async function getEmployeeInfo() {
  try {
    const adminUserId = userStore.getAdminUserId
    const res = await http.get(`/glsb/getEmployeeInfo?id=${adminUserId}`)
    if (res.data.result === 'success') {
      const info = res.data.data
      leaveForm.employeeName = info.name
      leaveForm.phone = info.phone || ''
    } else {
      ElMessage.error(res.data.error || '获取员工信息失败')
    }
  } catch (e) {
    ElMessage.error('获取员工信息失败: ' + e.message)
  }
}

/* ---------- 提交申请 ---------- */
async function submitLeaveApplication() {
  // 1. 表单基础校验
  await leaveFormRef.value.validate()

  // 2. 【新增】强校验：结束时间 ≥ 开始时间
  if (
      leaveForm.endDate &&
      new Date(leaveForm.endDate) < new Date(leaveForm.startDate)
  ) {
    ElMessage.error('请假结束时间不能小于请假开始时间')
    return
  }

  try {
    const res = await http.post('/glsb/addOneLeave', {
      employeeId: userStore.getAdminUserId,
      startDate: leaveForm.startDate,
      endDate: leaveForm.endDate,
      reason: leaveForm.reason,
      status: '待审批'
    })
    if (res.data.result === 'success') {
      ElMessage.success('请假申请提交成功')
      // 重置表单
      leaveForm.startDate = null
      leaveForm.endDate = null
      leaveForm.reason = ''
    } else {
      ElMessage.error(res.data.error || '提交失败')
    }
  } catch (e) {
    ElMessage.error('提交请假申请失败: ' + e.message)
  }
}

/* ---------- 生命周期 ---------- */
onMounted(() => {
  getEmployeeInfo()
})
</script>

<style scoped>
.leave-application-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}
.page-title {
  text-align: center;
  margin-bottom: 20px;
}
.leave-form {
  width: 400px;
  margin: 0 auto;
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}
</style>